const db=require('../db/index')
const bcypt=require('bcryptjs')
const jwt=require('jsonwebtoken')
const {jwtConfig}=require('../utils/index')
exports.register=(req,res)=>{
//  //非空校验
//     if(Object.keys(req.body).length<2){
//         return res.interRes("用户密码不能为空！",'9999')
//     }
//非重校验
let userInfo=req.body
const sqstr='select * from user_tb where username=?'
db.query(sqstr,userInfo.username,(err,result)=>{
    if(err){return res.interRes(err,'9999')}
    if(result.length>0){
        return res.interRes('用户名已被占用，请重新设置','9999') 
    }
//插入新用户信息
userInfo.password=bcypt.hashSync(userInfo.password,5)
const sqStr2='insert into user_tb set ?'
db.query(sqStr2,{username:userInfo.username,password:userInfo.password},(err,result)=>{
    if(err||result.affectedRows!==1){
        return res.interRes(err,'9999')
    } else res.send('用户注册成功')
})
})
}

exports.login=(req,res)=>{
    const userInfo=req.body
    const queryStr='select * from user_tb where username=?'
    db.query(queryStr,userInfo.username,(err,result)=>{
        if(err){return res.interRes('出错啦')}
        if(result.length!==1){
            return res.interRes('无登录用户信息')
        }
        console.log(result);
        //使用bcryptjs compareSync校验密码
        const compareResult=bcypt.compareSync(userInfo.password,result[0].password)
        if(!compareResult)return res.interRes('登录失败')
        const userToken={...result[0],password:'',user_pic:''}
        let token=jwt.sign(userToken,jwtConfig.secret,{expiresIn:jwtConfig.expiresIn})
        res.send({
            status:'200',
            msg:'登录成功',
            token
        })
    })
 
}
